from rest_framework import serializers
from .models import Note, Tag, Category, NoteTag, NoteCategory, User

class TagSerializer(serializers.ModelSerializer):
    """标签序列化器"""

    class Meta:
        model = Tag
        fields = ['id', 'name', 'description', 'created_at', 'updated_at', 'is_active', 'color', 'created_by',
                  'note_count']
        read_only_fields = ['created_at', 'updated_at', 'created_by', 'note_count']


class NoteSerializer(serializers.ModelSerializer):
    """笔记序列化器"""
    user_username = serializers.CharField(source='user.username', read_only=True)
    tags = TagSerializer(many=True, read_only=True)

    class Meta:
        model = Note
        fields = [
            'id', 'title', 'content', 'plan_type', 'status',
            'priority', 'is_pinned', 'progress', 'reminder_time',
            'tags', 'created_at', 'updated_at', 'user_username'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'user_username']

    def validate(self, data):
        """
        添加自定义验证
        """
        # 如果是部分更新，只验证提供的字段
        if self.partial:
            return data
            
        # 完整更新时的验证
        if not any(field in data for field in ['title', 'content', 'is_pinned', 'status']):
            raise serializers.ValidationError('至少需要提供一个要更新的字段')
            
        if 'title' in data and not data['title'].strip():
            raise serializers.ValidationError({'title': '标题不能为空'})
            
        if 'content' in data and not data['content'].strip():
            raise serializers.ValidationError({'content': '内容不能为空'})
            
        return data


class CreateNoteSerializer(serializers.ModelSerializer):
    """创建笔记的序列化器"""
    class Meta:
        model = Note
        fields = [
            'title', 
            'content',
            'plan_type',
            'status',
            'priority',
            'start_time',
            'end_time',
            'reminder_time',
            'progress',
            'checklist',
            'is_pinned'
        ]

    def create(self, validated_data):
        user = self.context['request'].user
        note = Note.objects.create(user=user, **validated_data)
        return note


class CategorySerializer(serializers.ModelSerializer):
    """分类序列化器"""

    class Meta:
        model = Category
        fields = ['id', 'name', 'description', 'parent_category', 'order', 'icon', 'color', 'created_at', 'updated_at',
                  'is_active']
        read_only_fields = ['created_at', 'updated_at']


class NoteTagSerializer(serializers.ModelSerializer):
    """笔记标签关联序列化器"""
    tag = TagSerializer()  # 嵌套Tag序列化器

    class Meta:
        model = NoteTag
        fields = ['id', 'note', 'tag', 'created_at']
        read_only_fields = ['created_at']


class NoteCategorySerializer(serializers.ModelSerializer):
    """笔记分类关联序列化器"""
    category = CategorySerializer()  # 嵌套Category序列化器

    class Meta:
        model = NoteCategory
        fields = ['id', 'note', 'category', 'created_at']
        read_only_fields = ['created_at']